package com.mz.mattress.admin.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mz.mattress.admin.api.req.DeviceQueryReq;
import com.mz.mattress.admin.api.resp.DeviceSum;
import com.mz.mattress.admin.api.resp.IntegerCount;
import com.mz.mattress.admin.api.resp.SaveDeviceResp;
import com.mz.mattress.admin.mapper.DeviceMapper;
import com.mz.mattress.admin.mapper.MerchantMapper;
import com.mz.mattress.admin.service.DeviceService;
import com.mz.mattress.api.common.Constants;
import com.mz.mattress.api.common.Result;
import com.mz.mattress.api.entity.Device;
import com.mz.mattress.api.entity.Merchant;
import com.mz.mattress.api.enums.MerchantStatusEnum;
import com.mz.mattress.api.util.DateUtil;
import com.mz.mattress.api.util.StringTools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;
import java.util.Set;

import static com.mz.mattress.api.common.Constants.TXT_SPLIT;

@Service
@Slf4j
public class DeviceServiceImpl implements DeviceService {

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private MerchantMapper merchantMapper;

    @Override
    public Result<IPage<Device>> listPage(DeviceQueryReq req) {

        Page<Device> list = deviceMapper.listPage(req.newPage(), req.getId(), req.getProvince(), req.getCity(), req.getDistrict(),
                req.getMemberId(), req.getMerchantId(), req.getMerchantName(), req.getSaleId(), req.getTopSaleId(), req.getName(),
                req.getDeviceCode(), req.getStatus(), req.getOnline(), req.getStartTime(), req.getEndTime());

        return Result.ok(list);
    }

    @Override
    public Result<IPage<Device>> listPageMerchant(DeviceQueryReq req) {

        //也查询 一级销售
        Page<Device> list = deviceMapper.listPageMerchant(req.newPage(),
                req.getMemberId(), req.getMerchantId(), req.getSaleId(), req.getTopSaleId());

        return Result.ok(list);
    }

    @Override
    public Result<List<Device>> list(Integer merchantId) {
        List<Device> list = deviceMapper.selectByMerchantId(merchantId);
        return Result.ok(list);
    }

    @Override
    public Result<Device> getById(Serializable id) {
        Device device = deviceMapper.selectById(id);
        return Result.ok(device);
    }

    @Override
    public Result add(Device device) {

        if (StringTools.isEmpty(device.getDeviceCode())) {
            return Result.fail("请输入设备编码");
        }

        Integer count = deviceMapper.selectCountByDeviceCode(device.getDeviceCode());
        if (count == 0) {
            device.setProductKey(PRODUCT_KEY);
            device.setWorkStatus(0);
            device.setOnline(1);
            device.setStatus(0);
            device.setMerchantId(0);
            device.setMerchantName("平台");
            deviceMapper.insert(device);
            return Result.ok();
        }

        return Result.fail("设备编码已存在");
    }

    @Override
    public Result<SaveDeviceResp> save(String content) {

        if (StringTools.isEmpty(content)) {
            return Result.ok();
        }

        String[] list = content.split(TXT_SPLIT);

        int success = 0;
        int fail = 0;

        for (String deviceCode : list) {
            deviceCode = deviceCode.trim();
            Integer count = deviceMapper.selectCountByDeviceCode(deviceCode);
            if (count == 0) {
                Device device = new Device();
                device.setDeviceCode(deviceCode);
                device.setProductKey(PRODUCT_KEY);
                device.setWorkStatus(0);
                device.setOnline(1);
                device.setStatus(0);
                device.setMerchantId(0);
                device.setMerchantName("平台");
                deviceMapper.insert(device);
                ++success;
            } else {
                log.info("deviceCode={},already_exist", deviceCode);
                ++fail;
            }
        }
        SaveDeviceResp resp = new SaveDeviceResp();
        resp.setSuccess(success);
        resp.setFail(fail);

        return Result.ok(resp);
    }

    @Override
    public Result bind(Integer merchantId, String deviceCode) {

        Merchant merchant = merchantMapper.selectById(merchantId);
        if (merchant == null) {
            return Result.fail("找不到商家");
        }

        Device device = deviceMapper.selectByDeviceCode(deviceCode);
        if (device == null) {
            return Result.fail("找不到设备");
        }

        if (device.getMerchantId() != null &&
                device.getMerchantId() != Constants.SYS_MERCHANT_ID &&
                !device.getMerchantId().equals(merchantId)) {
            return Result.fail("该设备已绑定商户ID=" + device.getMerchantId());
        }

        Device update = new Device();
        update.setId(device.getId());
        update.setMemberId(merchant.getMemberId());
        update.setDeviceCode(deviceCode);
        update.setMerchantId(merchantId);
        update.setMerchantName(merchant.getName());
        update.setSaleId(merchant.getSaleId());
        update.setTopSaleId(merchant.getTopSaleId());
        update.setInvestorId(merchant.getInvestorId());
        update.setBindTime(DateUtil.getNowDateTime());
        deviceMapper.updateById(update);

        //更新销售绑定设备数 +1
//        if (merchant.getSaleId() != null) {
//
//            saleMapper.updateDeviceBind(merchant.getSaleId());
//
//            if (merchant.getTopSaleId() != null &&
//                    !merchant.getSaleId().equals(merchant.getTopSaleId())) {
//                saleMapper.updateDeviceBind(merchant.getTopSaleId());
//            }
//
//        }

//        if (merchant.getStatus() != MerchantStatusEnum.OPENING.getValue()) {
//            //更新到营业中
//            Merchant update2 = new Merchant();
//            update2.setId(merchant.getId());
//            update2.setStatus(MerchantStatusEnum.OPENING.getValue());
//            merchantMapper.updateById(update2);
//        }

        Integer count = deviceMapper.selectCountByMerchantId(merchantId);

        Merchant update2 = new Merchant();
        update2.setId(merchantId);
        update2.setStatus(MerchantStatusEnum.OPENING.getValue());
        update2.setDeviceCount(count);
        merchantMapper.updateById(update2);

        return Result.ok();
    }

    @Override
    public Result unbind(Integer id) {

        Device device = deviceMapper.selectById(id);
        if (device == null) {
            return Result.fail("找不到设备");
        }

        if (device.getMerchantId() == null || device.getMerchantId() == 0) {
            return Result.fail("该设备已解绑");
        }

//        Merchant merchant = merchantMapper.selectById(device.getMerchantId());
//        if (merchant == null) {
//            return Result.fail("找不到商家");
//        }

//        //更新销售绑定设备数 -1
//        if (merchant.getSaleId() != null) {
//
//            saleMapper.updateDeviceUnbind(merchant.getSaleId());
//
//            if (merchant.getTopSaleId() != null &&
//                    !merchant.getSaleId().equals(merchant.getTopSaleId())) {
//                saleMapper.updateDeviceUnbind(merchant.getTopSaleId());
//            }
//
//        }

        deviceMapper.clearMerchantId(id);

        if (device.getMerchantId() != null) {
            Integer count = deviceMapper.selectCountByMerchantId(device.getMerchantId());

            Merchant update = new Merchant();
            update.setId(device.getMerchantId());
            update.setDeviceCount(count);
            merchantMapper.updateById(update);
        }

        return Result.ok();
    }

    @Override
    public Result updateStatus(Integer id, Integer status) {
        Device update = new Device();
        update.setId(id);
        update.setStatus(status);
        deviceMapper.updateById(update);

        return Result.ok();
    }

//    public void addDevice(String imei) {
//
//        imei = imei.trim();
//        Integer count = deviceMapper.selectByImei(imei);
//        if (count == 0) {
//            Device device = new Device();
//            device.setImei(imei);
//            deviceMapper.insert(device);
//        } else {
//            log.info("imei={},already_exist", imei);
//        }
//    }

    @Override
    public Result updateById(Device device) {

        String deviceCode = device.getDeviceCode();

        if (StringTools.isNotEmpty(deviceCode)) {
            Device one = deviceMapper.selectByDeviceCode(deviceCode);
            if (one != null && !one.getId().equals(device.getId())) {
                return Result.fail("该设备编码已存在");
            }
        }

        //不能改
        device.setMerchantId(null);
        device.setMerchantName(null);
        device.setTopSaleId(null);
        device.setSaleId(null);

        deviceMapper.updateById(device);

        return Result.ok();
    }

    @Override
    public Result deleteByIds(Set<Integer> ids) {
        deviceMapper.deleteBatchIds(ids);
        return Result.ok();
    }

    @Override
    public Result<DeviceSum> deviceSum(Integer typeId, Long memberMerId) {

        DeviceSum sum = new DeviceSum();

        List<IntegerCount> deviceCount = null;
        if (typeId.equals(Constants.TYPE_ID_ALL)) {
            //查看全部门店
            deviceCount = deviceMapper.selectSumByMemberId(memberMerId);
        } else {
            //单个门店
            deviceCount = deviceMapper.selectSumByColumn("merchant_id", typeId);
        }

        int total = 0;
        int off = 0;
        for (IntegerCount statusCount : deviceCount) {
            //1online在线 0offline离线
            if (statusCount.getStatus() == 0) {
                off = statusCount.getCount();
            }
            total += statusCount.getCount();
        }

        sum.setDeviceTotal(total);
        sum.setDeviceOff(off);
        sum.setDeviceOn(total - off);

        return Result.ok(sum);
    }

    @Override
    public Result genDeviceName() {

        String start = "MZA";
        Integer index = 0;

//        List<Integer> list = deviceMapper.demoList();

        List<Integer> list = deviceMapper.deviceList();

        for (int i = 0; i < list.size(); i++) {

            String name = String.format("%s%03d", start, i + 1);
            System.out.println(name);

            Device update = new Device();
            update.setId(list.get(i));
            update.setName(name);
            deviceMapper.updateById(update);

        }


//        for (int i = 1; i < 200; i++) {
//
//            String name = String.format("%s%03d", start, i);
//            System.out.println(name);
//
//        }


        return null;
    }

//    public static String genName(String start) {
//
//        System.out.println(String.format("%03d", 33));
//        System.out.println(String.format("%03d", 1));
//        System.out.println(String.format("%03d", 106));
//
//    }

    public static void main(String[] args) {

        String start = "MZZ";
        for (int i = 1; i < 200; i++) {

            String name = String.format("%s%03d", start, i);
            System.out.println(name);

        }

        System.out.println(String.format("%03d", 33));
        System.out.println(String.format("%03d", 1));
        System.out.println(String.format("%03d", 106));

        String text = "第一行\n第二行\r\n第三行，订单,ggg"; // 包含不同格式的换行符
        String[] lines = text.split("\n|\r\n|,|，"); // 使用正则表达式分割

        for (String line : lines) {
            System.out.println(line);
        }
    }
}
